package com.googlecode.restitory.gae.rhino;

import java.io.CharArrayReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.RequestService;
import com.googlecode.restitory.gae.Response;
import com.googlecode.restitory.gae.TextContent;
import com.googlecode.restitory.gae.Type;
import com.googlecode.restitory.gae.hook.DefaultRequestService;

public class RhinoRepo extends ScriptableObject {

	private static final long serialVersionUID = 8429944950317637969L;

	public static void config(ScriptableObject scope, Context ctx) {
		try {
			ScriptableObject.defineClass(scope, RhinoRepo.class);
			Scriptable s = ctx.newObject(scope, "Repo");
			scope.put("repo", scope, s);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public String getClassName() {
		return "Repo";
	}

	public static Object jsFunction_source(Context cx, Scriptable thisObj,
			Object[] args, Function funObj) {
		try {
			String path = (String) args[0];
			RequestService service = getService();
			Response resp = service.execute(new Request(Type.GET, path));
			if (resp.getCode() != 200) {
				throw new RuntimeException("error: " + resp);
			}
			if (!resp.getContentType().startsWith("application/javascript")) {
				throw new RuntimeException("error: " + resp);
			}
			TextContent content = (TextContent) resp.getContent();
			char[] chars = content.getValue();
			Object ret = cx.evaluateReader(thisObj, new CharArrayReader(chars),
					"repo:" + path, 1, null);
			// Scriptable parent = ScriptableObject.getTopLevelScope(thisObj);
			// return Context.javaToJS(ret, parent);
			return ret;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static RequestService getService() {
		return DefaultRequestService.createService();
	}

}
